'use client';

import { useState, useEffect } from 'react';

interface BlogPost {
  id: number;
  title: string;
  excerpt: string;
  date: string;
  slug: string;
  category: string;
  readTime: string;
}

interface User {
  id: number;
  name: string;
  email: string;
  role: string;
  joinDate: string;
  avatar: string;
}

export default function ApiDemoPage() {
  const [posts, setPosts] = useState<BlogPost[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const fetchPosts = async (category?: string) => {
    setLoading(true);
    setError('');
    try {
      const url = category ? `/api/posts?category=${category}` : '/api/posts';
      const response = await fetch(url);
      const data = await response.json();
      
      if (data.success) {
        setPosts(data.data);
      } else {
        setError(data.error || '获取文章失败');
      }
    } catch {
      setError('网络错误');
    } finally {
      setLoading(false);
    }
  };

  const fetchUsers = async (role?: string) => {
    setLoading(true);
    setError('');
    try {
      const url = role ? `/api/users?role=${role}` : '/api/users';
      const response = await fetch(url);
      const data = await response.json();
      
      if (data.success) {
        setUsers(data.data);
      } else {
        setError(data.error || '获取用户失败');
      }
    } catch {
      setError('网络错误');
    } finally {
      setLoading(false);
    }
  };

  // UI 仅用于 GET 示例，不提供创建操作

  useEffect(() => {
    fetchPosts();
    fetchUsers();
  }, []);

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-6xl mx-auto px-4 py-12">
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">API 演示</h1>
          <p className="text-xl text-gray-600">
            展示 Next.js API 路由的强大功能
          </p>
        </div>

        {error && (
          <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
            {error}
          </div>
        )}

        <div className="grid lg:grid-cols-2 gap-8">
          {/* 博客文章 API */}
          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-2xl font-bold text-gray-900">博客文章 API</h2>
              <button
                onClick={() => fetchPosts()}
                disabled={loading}
                className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 disabled:opacity-50"
              >
                {loading ? '加载中...' : '刷新'}
              </button>
            </div>

            <div className="flex gap-2 mb-4">
              <button
                onClick={() => fetchPosts('技术')}
                className="bg-gray-200 text-gray-700 px-3 py-1 rounded text-sm hover:bg-gray-300"
              >
                技术
              </button>
              <button
                onClick={() => fetchPosts('设计')}
                className="bg-gray-200 text-gray-700 px-3 py-1 rounded text-sm hover:bg-gray-300"
              >
                设计
              </button>
              <button
                onClick={() => fetchPosts('架构')}
                className="bg-gray-200 text-gray-700 px-3 py-1 rounded text-sm hover:bg-gray-300"
              >
                架构
              </button>
              <button
                onClick={() => fetchPosts()}
                className="bg-gray-200 text-gray-700 px-3 py-1 rounded text-sm hover:bg-gray-300"
              >
                全部
              </button>
            </div>

            <div className="space-y-3 mb-4">
              {posts.map((post) => (
                <div key={post.id} className="border border-gray-200 rounded p-3">
                  <h3 className="font-semibold text-gray-900">{post.title}</h3>
                  <p className="text-sm text-gray-600">{post.excerpt}</p>
                  <div className="flex items-center gap-2 mt-2">
                    <span className="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded">
                      {post.category}
                    </span>
                    <span className="text-xs text-gray-500">{post.readTime}</span>
                  </div>
                </div>
              ))}
            </div>

            {/* 创建操作已移除 */}
          </div>

          {/* 用户 API */}
          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-2xl font-bold text-gray-900">用户 API</h2>
              <button
                onClick={() => fetchUsers()}
                disabled={loading}
                className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 disabled:opacity-50"
              >
                {loading ? '加载中...' : '刷新'}
              </button>
            </div>

            <div className="flex gap-2 mb-4">
              <button
                onClick={() => fetchUsers('开发者')}
                className="bg-gray-200 text-gray-700 px-3 py-1 rounded text-sm hover:bg-gray-300"
              >
                开发者
              </button>
              <button
                onClick={() => fetchUsers('设计师')}
                className="bg-gray-200 text-gray-700 px-3 py-1 rounded text-sm hover:bg-gray-300"
              >
                设计师
              </button>
              <button
                onClick={() => fetchUsers('产品经理')}
                className="bg-gray-200 text-gray-700 px-3 py-1 rounded text-sm hover:bg-gray-300"
              >
                产品经理
              </button>
              <button
                onClick={() => fetchUsers()}
                className="bg-gray-200 text-gray-700 px-3 py-1 rounded text-sm hover:bg-gray-300"
              >
                全部
              </button>
            </div>

            <div className="space-y-3 mb-4">
              {users.map((user) => (
                <div key={user.id} className="border border-gray-200 rounded p-3">
                  <div className="flex items-center gap-3">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={user.avatar}
                      alt={user.name}
                      className="w-10 h-10 rounded-full"
                    />
                    <div>
                      <h3 className="font-semibold text-gray-900">{user.name}</h3>
                      <p className="text-sm text-gray-600">{user.email}</p>
                      <div className="flex items-center gap-2 mt-1">
                        <span className="bg-green-100 text-green-800 text-xs px-2 py-1 rounded">
                          {user.role}
                        </span>
                        <span className="text-xs text-gray-500">{user.joinDate}</span>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            {/* 创建操作已移除 */}
          </div>
        </div>

        <div className="mt-12 bg-white rounded-lg shadow-md p-6">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">API 端点说明</h2>
          <div className="grid md:grid-cols-2 gap-6">
            <div>
              <h3 className="text-lg font-semibold mb-2">博客文章 API</h3>
              <ul className="space-y-2 text-sm text-gray-600">
                <li><code>GET /api/posts</code> - 获取所有文章</li>
                <li><code>GET /api/posts?category=技术</code> - 按分类筛选</li>
                <li><code>GET /api/posts?limit=2</code> - 限制返回数量</li>
                {/* POST 示例已移除 */}
              </ul>
            </div>
            <div>
              <h3 className="text-lg font-semibold mb-2">用户 API</h3>
              <ul className="space-y-2 text-sm text-gray-600">
                <li><code>GET /api/users</code> - 获取所有用户</li>
                <li><code>GET /api/users?role=开发者</code> - 按角色筛选</li>
                {/* POST 示例已移除 */}
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
